import { ReactNode, useState } from 'react';
import { Link, useLocation, useNavigate } from 'react-router-dom';
import { 
  LayoutDashboard, 
  Wifi, 
  MapPin, 
  Globe2, 
  BarChart3, 
  Settings, 
  BookOpen,
  Menu,
  X,
  LogOut,
  User,
  Sun,
  Moon,
  Languages,
  ChevronLeft,
  ChevronRight,
  ShoppingCart,
  Package,
  ChevronDown,
  ChevronUp,
  Users,
  MessageSquare
} from 'lucide-react';
import { useLanguage } from '@kernelproxy/i18n';
import { useTheme } from '@kernelproxy/theme';
import { useAuth } from '../contexts/AuthContext';
import { useCart } from '../contexts/CartContext';
import LoadingBar from './LoadingBar';

interface DashboardLayoutProps {
  children: ReactNode;
}

const DashboardLayout = ({ children }: DashboardLayoutProps) => {
  const location = useLocation();
  const navigate = useNavigate();
  const { language, setLanguage } = useLanguage();
  const { theme, setTheme } = useTheme();
  const { getItemCount } = useCart();
  
  const toggleTheme = () => {
    setTheme(theme === 'dark' ? 'light' : 'dark');
  };
  const { user, logout, isAdmin, getUserAvatarUrl } = useAuth();
  const [sidebarOpen, setSidebarOpen] = useState(false);
  const [sidebarCollapsed, setSidebarCollapsed] = useState(false);
  const [purchaseMenuOpen, setPurchaseMenuOpen] = useState(false);
  const [settingsMenuOpen, setSettingsMenuOpen] = useState(false);
  const [loading, setLoading] = useState(false);

  const cartItemCount = getItemCount();

  const getLink = (path: string) => {
    return language === 'zh-CN' ? `/zh-CN${path}` : path;
  };

  const allMenuItems = [
    {
      title: language === 'zh-CN' ? '概览' : 'Overview',
      icon: LayoutDashboard,
      path: '/dashboard',
    },
    {
      title: language === 'zh-CN' ? 'IPv6购买' : 'IPv6 Purchase',
      icon: ShoppingCart,
      path: '/dashboard/purchase',
      isSubmenu: true,
      submenuItems: [
        {
          title: language === 'zh-CN' ? '动态住宅IPv6' : 'Dynamic Residential IPv6',
          path: '/dashboard/purchase-dynamic-residential',
          external: false,
        },
        {
          title: language === 'zh-CN' ? '静态住宅IPv6' : 'Static Residential IPv6',
          path: '/dashboard/purchase-static-residential',
          external: false,
        },
        {
          title: language === 'zh-CN' ? '数据中心IPv6' : 'Datacenter IPv6',
          path: '/dashboard/purchase-datacenter-ipv6',
          external: false,
        },
      ],
    },
    {
      title: language === 'zh-CN' ? '我的订单' : 'My Orders',
      icon: Package,
      path: '/dashboard/orders',
    },
    {
      title: language === 'zh-CN' ? '动态住宅IPv6' : 'Dynamic Residential IPv6',
      icon: Wifi,
      path: '/dashboard/dynamic',
    },
    {
      title: language === 'zh-CN' ? '静态住宅IPv6' : 'Static Residential IPv6',
      icon: MapPin,
      path: '/dashboard/static',
    },
    {
      title: language === 'zh-CN' ? '数据中心IPv6' : 'Datacenter IPv6',
      icon: Globe2,
      path: '/dashboard/ipv6',
    },
    {
      title: language === 'zh-CN' ? '监控分析' : 'Analytics',
      icon: BarChart3,
      path: '/dashboard/analytics',
    },
    {
      title: language === 'zh-CN' ? 'API文档' : 'API Docs',
      icon: BookOpen,
      path: '/dashboard/api-docs',
    },
    {
      title: language === 'zh-CN' ? '联盟营销' : 'Affiliates',
      icon: Users,
      path: '/dashboard/affiliates',
    },
    {
      title: language === 'zh-CN' ? '提交工单' : 'Submit Ticket',
      icon: MessageSquare,
      path: '/dashboard/support',
    },
    // Admin-only menu items
    ...(isAdmin ? [
      {
        title: language === 'zh-CN' ? '用户管理' : 'User Management',
        icon: Users,
        path: '/dashboard/admin/users',
        adminOnly: true,
      },
    ] : []),
    {
      title: language === 'zh-CN' ? '设置' : 'Settings',
      icon: Settings,
      path: '/dashboard/settings',
      submenu: [
        {
          title: language === 'zh-CN' ? '账户设置' : 'Account Settings',
          path: '/dashboard/settings',
        },
        {
          title: language === 'zh-CN' ? '计费套餐' : 'Billing & Plans',
          path: '/dashboard/billing',
        },
      ],
    },
  ];

  // Filter menu items based on user role
  const menuItems = allMenuItems;

  const handleLogout = async () => {
    console.log('DashboardLayout: Logout button clicked');
    setLoading(true);
    try {
      await logout();
      console.log('DashboardLayout: Logout completed, navigating to login page');
      navigate(getLink('/login'));
    } catch (error) {
      console.error('DashboardLayout: Logout error:', error);
      // Navigate anyway to clear the UI
      navigate(getLink('/login'));
    } finally {
      setLoading(false);
    }
  };

  const toggleLanguage = () => {
    setLoading(true);
    const newLang = language === 'zh-CN' ? 'en' : 'zh-CN';
    setLanguage(newLang);
    
    // Get current path without language prefix
    let currentPath = location.pathname;
    if (currentPath.startsWith('/zh-CN')) {
      currentPath = currentPath.replace(/^\/zh-CN/, '');
    }
    
    // Navigate to the same path with new language
    const newPath = newLang === 'zh-CN' ? `/zh-CN${currentPath}` : currentPath;
    navigate(newPath);
    
    setTimeout(() => setLoading(false), 400);
  };

  const handleNavigate = (path: string, external?: boolean) => {
    if (external) {
      window.open(path, '_blank');
    } else {
      setLoading(true);
      navigate(getLink(path));
      setSidebarOpen(false);
      setTimeout(() => setLoading(false), 400);
    }
  };

  return (
    <div className="min-h-screen bg-gray-50 dark:bg-gray-900 transition-colors duration-300">
      {/* Loading Bar */}
      <LoadingBar loading={loading} />
      
      {/* Top Navigation Bar */}
      <nav className="bg-white dark:bg-gray-800 border-b border-gray-200 dark:border-gray-700 fixed w-full z-30 top-0">
        <div className="px-4 sm:px-6 lg:px-8">
          <div className="flex items-center justify-between h-16">
            {/* Left side */}
            <div className="flex items-center">
              <button
                onClick={() => setSidebarOpen(!sidebarOpen)}
                className="lg:hidden p-2 rounded-md text-gray-600 dark:text-gray-400 hover:bg-gray-100 dark:hover:bg-gray-700"
              >
                {sidebarOpen ? <X size={24} /> : <Menu size={24} />}
              </button>
              {/* Desktop collapse button */}
              <button
                onClick={() => setSidebarCollapsed(!sidebarCollapsed)}
                className="hidden lg:block p-2 rounded-md text-gray-600 dark:text-gray-400 hover:bg-gray-100 dark:hover:bg-gray-700"
              >
                {sidebarCollapsed ? <ChevronRight size={24} /> : <ChevronLeft size={24} />}
              </button>
              <Link to={getLink('/dashboard')} className="flex items-center space-x-2 ml-4">
                <img src="/logo.svg" alt="KernelProxy" className="w-8 h-8" />
                <div className="flex items-center">
                  <span className="text-xl font-bold text-[#00d4ff]">kernel</span>
                  <span className="text-xl font-bold text-gray-900 dark:text-white">Proxy</span>
                </div>
              </Link>
            </div>

            {/* Right side */}
            <div className="flex items-center space-x-4">
              {/* Theme Toggle */}
              <button
                onClick={toggleTheme}
                className="p-2 rounded-lg text-gray-600 dark:text-gray-400 hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors"
              >
                {theme === 'dark' ? <Sun size={20} /> : <Moon size={20} />}
              </button>

              {/* Language Toggle */}
              <button
                onClick={toggleLanguage}
                className="p-2 rounded-lg text-gray-600 dark:text-gray-400 hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors"
              >
                <Languages size={20} />
              </button>

              {/* Shopping Cart */}
              <button
                onClick={() => handleNavigate('/dashboard/cart')}
                className="p-2 rounded-lg text-gray-600 dark:text-gray-400 hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors relative"
              >
                <ShoppingCart size={20} />
                {cartItemCount > 0 && (
                  <span className="absolute -top-1 -right-1 bg-red-600 text-white text-xs font-bold rounded-full h-5 w-5 flex items-center justify-center">
                    {cartItemCount > 99 ? '99+' : cartItemCount}
                  </span>
                )}
              </button>

              {/* User Menu */}
              <div className="flex items-center space-x-3 pl-4 border-l border-gray-200 dark:border-gray-700">
                <div className="hidden sm:block text-right">
                  <p className="text-sm font-medium text-gray-900 dark:text-white">
                    {user?.name || 'User'}
                    {isAdmin && (
                      <span className="ml-2 px-2 py-0.5 text-xs font-semibold bg-gradient-to-r from-purple-600 to-pink-600 text-white rounded-full">
                        {language === 'zh-CN' ? '管理员' : 'Admin'}
                      </span>
                    )}
                  </p>
                  <p className="text-xs text-gray-500 dark:text-gray-400">
                    {user?.email || 'user@example.com'}
                  </p>
                </div>
                <div className="relative w-10 h-10 rounded-full overflow-hidden bg-gradient-to-br from-blue-500 to-purple-600 flex items-center justify-center">
                  {getUserAvatarUrl() ? (
                    <img 
                      src={getUserAvatarUrl()} 
                      alt={user?.name || 'User'} 
                      className="w-full h-full object-cover"
                      onError={(e) => {
                        // Fallback to User icon if image fails to load
                        (e.target as HTMLImageElement).style.display = 'none';
                      }}
                    />
                  ) : (
                    <User size={20} className="text-white" />
                  )}
                </div>
                <button
                  onClick={handleLogout}
                  className="p-2 rounded-lg text-gray-600 dark:text-gray-400 hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors"
                  title={language === 'zh-CN' ? '登出' : 'Logout'}
                >
                  <LogOut size={20} />
                </button>
              </div>
            </div>
          </div>
        </div>
      </nav>

      {/* Sidebar */}
      <aside
        className={`fixed left-0 top-16 h-[calc(100vh-4rem)] bg-white dark:bg-gray-800 border-r border-gray-200 dark:border-gray-700 overflow-y-auto transition-all duration-300 z-20 ${
          sidebarOpen ? 'translate-x-0' : '-translate-x-full lg:translate-x-0'
        } ${sidebarCollapsed ? 'lg:w-20' : 'lg:w-72'} w-72`}
      >
        <nav className={`p-4 space-y-2 ${sidebarCollapsed ? 'flex flex-col items-center' : ''}`}>
          {menuItems.map((item, index) => {
            const isActive = location.pathname === getLink(item.path) || 
                           (item.path === '/dashboard' && location.pathname === getLink('/dashboard/'));
            
            // Submenu item (IPv6 Purchase or Settings)
            if (item.isSubmenu || item.submenu) {
              const isOpen = item.title.includes('IPv6') || item.title.includes('购买') 
                ? purchaseMenuOpen 
                : settingsMenuOpen;
              const setOpen = item.title.includes('IPv6') || item.title.includes('购买')
                ? setPurchaseMenuOpen
                : setSettingsMenuOpen;
              const submenuItems = item.submenuItems || item.submenu;
              
              return (
                <div key={index}>
                  <button
                    onClick={() => setOpen(!isOpen)}
                    className={`flex items-center ${sidebarCollapsed ? 'justify-center' : 'justify-between'} w-full px-4 py-3 rounded-lg transition-colors ${
                      isOpen
                        ? 'bg-blue-50 dark:bg-blue-900/20 text-blue-600 dark:text-blue-400'
                        : 'text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700'
                    }`}
                    title={sidebarCollapsed ? item.title : undefined}
                  >
                    <div className={`flex items-center ${sidebarCollapsed ? '' : 'space-x-3'}`}>
                      <item.icon size={20} className="flex-shrink-0" />
                      {!sidebarCollapsed && <span className="font-medium">{item.title}</span>}
                    </div>
                    {!sidebarCollapsed && (
                      isOpen ? <ChevronUp size={16} /> : <ChevronDown size={16} />
                    )}
                  </button>
                  {isOpen && !sidebarCollapsed && (
                    <div className="ml-4 mt-2 space-y-1 border-l-2 border-gray-200 dark:border-gray-700 pl-4">
                      {submenuItems?.map((subitem: any, subindex) => (
                        <button
                          key={subindex}
                          onClick={() => handleNavigate(subitem.path, subitem.external)}
                          className="flex items-center w-full px-4 py-2 text-sm rounded-lg text-gray-600 dark:text-gray-400 hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors"
                        >
                          {subitem.title}
                        </button>
                      ))}
                    </div>
                  )}
                </div>
              );
            }
            
            // Regular menu item
            return (
              <button
                key={index}
                onClick={() => handleNavigate(item.path)}
                className={`flex items-center ${sidebarCollapsed ? 'justify-center' : 'space-x-3'} w-full px-4 py-3 rounded-lg transition-colors ${
                  isActive
                    ? 'bg-blue-50 dark:bg-blue-900/20 text-blue-600 dark:text-blue-400'
                    : 'text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700'
                } ${(item as any).adminOnly ? 'border-2 border-purple-500/30' : ''}`}
                title={sidebarCollapsed ? item.title : undefined}
              >
                <item.icon size={20} className="flex-shrink-0" />
                {!sidebarCollapsed && (
                  <div className="flex items-center justify-between w-full">
                    <span className="font-medium">{item.title}</span>
                    {(item as any).adminOnly && (
                      <span className="px-2 py-0.5 text-xs font-semibold bg-gradient-to-r from-purple-600 to-pink-600 text-white rounded-full">
                        {language === 'zh-CN' ? '管理' : 'Admin'}
                      </span>
                    )}
                  </div>
                )}
              </button>
            );
          })}
        </nav>
      </aside>

      {/* Main Content */}
      <main className={`pt-16 transition-all duration-300 ${sidebarCollapsed ? 'lg:pl-20' : 'lg:pl-72'}`}>
        <div className="p-6 lg:p-8">
          {children}
        </div>
      </main>

      {/* Mobile Overlay */}
      {sidebarOpen && (
        <div
          className="fixed inset-0 bg-black bg-opacity-50 z-10 lg:hidden"
          onClick={() => setSidebarOpen(false)}
        />
      )}
    </div>
  );
};

export default DashboardLayout;
